<template>
  <el-container class="exchange">
    <el-main>
      <div class="card-list">
        <el-card shadow="never">
          <el-form label-position="right" label-width="6rem">
            <el-row :gutter="20">
              <el-col :span="10">
                <el-form-item label="商户名称：">
                  <el-input v-model="searchParams.ownerName" placeholder="请输入内容" :disabled="true">
                    <el-button slot="append" icon="el-icon-search" @click="openSelectShopDialog(true)" />
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="设备名称：">
                  <el-select v-model="searchParams.printerId" placeholder="请选择">
                    <el-option label="全部" key="" value="" />
                    <el-option
                      v-for="item in equipmentList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="连接状态：">
                  <el-select v-model="searchParams.connectStatus">
                    <el-option label="全部" value="" />
                    <el-option label="在线" :value="1" />
                    <el-option label="离线" :value="0" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <SearchButton  :default-params="searchParams" @refreshParams="refreshParams" @getList="getList1"  />
          </el-form>
        </el-card>
        <el-card shadow="never" class="tableCard">
          <vxe-toolbar :refresh="{query: getList1}">
            <template v-slot:buttons>
              <el-button type="primary" icon="el-icon-plus" @click="openDialog('', false)">新增</el-button>
            </template>
          </vxe-toolbar>
          <vxe-table
            ref="xTree"
            border
            row-key
            resizable
            highlight-hover-row
            :auto-resize="true"
            :data="list"
            :span-method="rowspanMethod"
            width
            max-height="500"
            row-id="id"
            highlight-current-row
            text-algin="center"
            :print-config="{}"
            header-align="center"
          >
            <vxe-table-column
              field="ownerName"
              width="200"
              align="left"
              title="商户名称"
            />
            <vxe-table-column
              field="brandName"
              width="180"
              align="left"
              title="品牌名称"
            />
            <vxe-table-column
              field="storeNo"
              width="120"
              align="left"
              title="铺位号"
            />
            <vxe-table-column
              field="bizStatusName"
              width="100"
              align="center"
              title="商户状态"
            />
            <vxe-table-column
              field="printerName"
              width="160"
              align="left"
              title="设备名称"
            />
            <vxe-table-column
              field="serialNo"
              width="180"
              align="left"
              title="设备序列号"
            />
            <vxe-table-column
              field="connectStatusDesc"
              width="100"
              align="center"
              title="连接状态"
            />
            <vxe-table-column
              field="ipAddress"
              width="150"
              align="center"
              title="连接IP"
            />

            <vxe-table-column
              title="备注"
              field="remark"
              align="left"
              min-width="250"
            />
            <vxe-table-column
              title="状态"
              width="80"
              align="center"
              slots="default"
            >
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.publishStatus"
                  :inactive-value="0"
                  :active-value="1"
                  active-text
                  inactive-text
                  @change="changeState(scope)"
                />
              </template>
            </vxe-table-column>
            <vxe-table-column
              title="操作"
              fixed="right"
              align="center"
              width="120"
            >
              <template slot-scope="scope">
                <div class="drag-btn">
                  <el-button
                    type="text"
                    size="mini"
                    @click="openDialog(scope.row.id, true)"
                  >查看</el-button>
                  <el-button
                    v-if="scope.row.publishStatus != 1"
                    type="text"
                    size="mini"
                    @click="openDialog(scope.row.id, false)"
                  >编辑</el-button>
                  <el-button
                    v-if="scope.row.publishStatus != 1"
                    type="text"
                    size="mini"
                    @click="delClick(scope.row.id)"
                  >删除</el-button>
                </div>
              </template>
            </vxe-table-column>
          </vxe-table>
          <vxe-pager
            :current-page.sync="searchParams.tableCurrentPage"
            :page-size.sync="searchParams.pageSize"
            :total="total"
            :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
            @page-change="getList()"
          />
        </el-card>
        <el-dialog :close-on-click-modal="false" :modal="false" :visible.sync="dialogVisible" title="设备绑定">
          <el-form ref="ruleForm" :model="params" label-width="7rem" :rules="rules">
            <el-row :gutter="40">
              <el-col :span="12">
                <el-form-item label="商户名称：" prop="ownerName">
                  <el-input v-model="params.ownerName" placeholder="请输入内容" :disabled="true">
                    <el-button slot="append" icon="el-icon-search" @click="openSelectShopDialog(false)" v-if="!disabledEdit"/>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="品牌名称：" prop="brandName">
                  <el-input v-model="params.brandName" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="铺位号：" prop="storeNo">
                  <el-input v-model="params.storeNo" disabled />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="设备名称：">
                  <el-select v-model="params.printerId" placeholder="请选择" :disabled="disabledEdit">
                    <el-option
                      v-for="item in equipmentList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设备序列号：" prop="serialNo">
                  <el-input v-model="params.serialNo"  :disabled="disabledEdit"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="IP地址：" prop="ipAddress">
                  <el-input v-model="params.ipAddress"  :disabled="disabledEdit"/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注：" prop="remark">
                  <el-input v-model="params.remark" type="textarea" :rows="2" :disabled="disabledEdit"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button v-if="!disabledEdit" type="primary" @click="submit">确 定</el-button>
          </div>
        </el-dialog>
          <el-dialog v-if="shopDialogVisible" width="60%" title="选择" :close-on-click-modal="false" :visible.sync="shopDialogVisible" append-to-body>
            <div class="card-list">
              <el-card shadow="never" class="selectCard searchColumn">
                <el-form ref="ruleShopForm" label-position="right" :model="shopParams" :rules="ShopRules" label-width="6rem">
                  <el-row :gutter="40">
                    <el-col :span="10">
                      <el-form-item label="名称：" prop="name">
                        <el-input v-model="shopParams.name" style="width: 240px;" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <SearchButton :default-params="chooseParams" @refreshParams="refreshShopParams" @getList="getShopList1" />
                    </el-col>
                  </el-row>
                </el-form>
              </el-card>
              <el-card shadow="never" class="tableCard">
                <vxe-toolbar :refresh="{query: getShopList}" />
                <vxe-table
                  ref="listShop"
                  border
                  resizable
                  highlight-hover-row
                  :auto-resize="true"
                  :data="shopList"
                  width
                  max-height="300"
                  highlight-current-row
                  text-algin="center"
                >
                  <vxe-table-column type="radio" width="80" />
                  <vxe-table-column min-width="220" field="name" title="商户名称" />
                  <vxe-table-column width="220" field="brandName" title="经营品牌" />
                  <vxe-table-column width="180" field="storeNo" title="铺位号" />
                  <vxe-table-column width="150" field="bizStatusName" title="经营状态" />
                </vxe-table>
                <vxe-pager
                  :current-page.sync="shopParams.pageNum"
                  :page-size.sync="shopParams.pageSize"
                  :total="shopTotal"
                  :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
                  @page-change="getShopList"
                />
              </el-card>
            </div>
            <div slot="footer" class="dialog-footer">
              <el-button @click="shopDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="clickShopSure">确定</el-button>
            </div>
          </el-dialog>
      </div>
      </el-main>
  </el-container>
</template>

<script>
import SearchButton from '@/components/SearchButton'
import {listShopBindPrinterEquipment,listPrinterEquipments, viewShopBindPrinterEquipment, delShopBindPrinterEquipment,addShopBindPrinterEquipment,modifyShopBindPrinterEquipment, changeShopBindPrinterEquipmentStatus} from '@/api/hardware'
import {getShopsPageList } from '@/api/tenement'
export default {
  components: {
    SearchButton
  },
  data() {
    return {
      title: '',
      disabledEdit: true,
      dialogVisible: false,
      shopDialogVisible: false,
      isSearchShopDialog: true,
      shopParams: {},
      shopTotal: 0,
      shopList: [],
      equipParams: {
        publishStatus: 1
      },
      searchParams: {
        equipmentId:'', // 收银机设备id
        ownerId:'', // 商户id
        ownerName:'', // 商户id
        connectStatus:'', // 连接状态 –0离线 –1在线 “”为全部 或者不传
        tableCurrentPage:1,
        pageSize:20,
      },
      params:{
        ownerName:'',
        brandName:'',
        storeNo:'',
        equipmentId:'',
        remark:''
      },
      rules:{},
      list: [],
      total: 0,
      equipmentList:[]
    }
  },
  created() {
    this.getList()
    this.equipments()
  },
  methods: {
    equipments(){
      listPrinterEquipments({... this.equipParams}).then(res =>{
        this.equipmentList = res
      })
    },
    refreshParams(params) {
      this.searchParams = params
      this.getList()
    },
    getList1(){
      this.searchParams.tableCurrentPage = 1
      this.getList()
    },
    // 列表
    getList() {
      listShopBindPrinterEquipment(this.searchParams).then(res =>{
        this.list = res.records
        this.total = res.total
      })
    },
    getShopList1() {
      this.shopParams.pageNum = 1
      this.getShopList()
    },
    refreshShopParams(params) {
      this.shopParams = params
    },
    clickShopSure() {
       const selectedRow = this.$refs.listShop.getRadioRecord()
       if(this.isSearchShopDialog){
         this.searchParams.ownerId = selectedRow.id
         this.searchParams.ownerName = selectedRow.name
       }else{
         this.params.ownerId = selectedRow.id
         this.params.ownerName = selectedRow.name
         this.params.storeNo = selectedRow.storeNo
         this.params.brandName = selectedRow.brandName
       }
    },
    getShopList() {
      getShopsPageList({ ...this.shopParams}).then((response) => {
        this.shopList = JSON.parse(
          JSON.stringify(response.records)
        )
        this.total = response.total
      })
    },
    openSelectShopDialog(bool){
      this.isSearchShopDialog = bool
      this.shopDialogVisible = true
    },
    // 详情
    openDialog(id, bool) {
       this.dialogVisible = true
       this.disabledEdit = bool
      if(id){
        this.flag = true
        viewShopBindPrinterEquipment(id).then(res =>{
          if(res){
            if(res.code){
              this.$message.error(`${res.msg}`);
            }else{
              this.params = res
            }
          }
        })
      }else{
        this.flag = false
        Object.keys(this.params).forEach(key => this.params[key] = '')
      }
    },
    // 删除
    delClick(id){
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delShopBindPrinterEquipment(id).then(res => {
          this.$message.success('删除成功!')
          this.getList()
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    changeState(scope) {
      this.list[scope.seq - 1].publishStatus =
        scope.row.publishStatus === 1 ? 0 : 1
      changeShopBindPrinterEquipmentStatus({
        id: scope.row.id,
        status: scope.row.publishStatus === 1 ? 0 : 1
      }).then((response) => {
        this.list[scope.seq - 1].publishStatus =
          scope.row.publishStatus === 1 ? 0 : 1
        this.$message.success(
          scope.row.publishStatus === 0 ? '禁用成功' : '启用成功'
        )
      })
    },
    // 保存
    submit(){
      if(this.flag){
        modifyShopBindPrinterEquipment(this.params).then(res=>{
          if(res){
            if(res.code){
              this.$message.error(`${res.msg}`);
            }else{
              this.$message.success('修改成功!')
              this.getList()
              this.dialogVisible = false
            }
          }
        })
      }else{
        addShopBindPrinterEquipment(this.params).then(res=>{
          if(res){
            if(res.code){
              this.$message.error(`${res.msg}`);
            }else{
              this.$message.success('保存成功!')
              this.getList()
              this.dialogVisible = false
            }
          }
        })
      }
    },
    // 通用行合并函数（将相同多列数据合并为一行）
    rowspanMethod({ row, _rowIndex, column, visibleData }) {
      const fields = ['ownerName', 'brandName', 'storeNo', 'bizStatusName']
      const cellValue = row[column.property]
      if (cellValue && fields.includes(column.property)) {
        const prevRow = visibleData[_rowIndex - 1]
        let nextRow = visibleData[_rowIndex + 1]
        if (prevRow && prevRow[column.property] === cellValue) {
          return { rowspan: 0, colspan: 0 }
        } else {
          let countRowspan = 1
          while (nextRow && nextRow[column.property] === cellValue) {
            nextRow = visibleData[++countRowspan + _rowIndex]
          }
          if (countRowspan > 1) {
            return { rowspan: countRowspan, colspan: 1 }
          }
        }
      }
    }
  }
}
</script>

<style>
</style>
